# -*- coding: utf-8 -*-
from liberHook.BaseHook import BaseHook
from liberLibs import utils
from liberLibs.library import Library
from liberLibs.path import Path
import maya.cmds as mc
import liberConfig


TEXTURE_NODE_ATTR_DICT = liberConfig.TEXTURE_NODE_ATTR_DICT


class Hook(BaseHook):
    def __init__(self, library, directory, ext, start, end):
        super(Hook, self).__init__(library, directory, ext, start, end)

    def execute(self):
        sels = mc.ls(sl=1)
        if len(sels) > 1:
            self.append_error("More than one node selected.")
            return
        node = sels[0]
        node_type = mc.nodeType(node)
        if node_type not in TEXTURE_NODE_ATTR_DICT.keys():
            self.append_error("%s not in the TEXTURE_NODE_ATTR_DICT" % node_type)
            return
        attr = "%s.%s" % (node, TEXTURE_NODE_ATTR_DICT.get(node_type))
        if node_type == "file":
            attr = "%s.computedFileTextureNamePattern" % node
        texture = mc.getAttr(attr)
        files = utils.get_texture_abs_path(texture)
        if not files:
            return
        path_num = len(files)
        for each in files:
            _ext = Path(each).ext()
            basename = Path(each).basename()
            if path_num == 1:
                new_path = "{directory}/files/{name}{_ext}".format(directory=self.directory,
                                                                   name=self.name, _ext=_ext)
            else:
                new_path = "{directory}/files/{basename}".format(directory=self.directory, basename=basename)
            utils.copy(each, new_path)

        if Library(self.library).auto_thumbnail():
            self.remove_thumbnail()
            try:
                utils.resize_image(str(files[0]), str(self.thumbnail))
            except Exception as e:
                print str(e)
